package com.usian.article.service.impl

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.usian.article.feign.BehaviorFeign
import com.usian.article.mapper.ApCollectionBehaviorMapper
import com.usian.model.behavior.dtos.CollectionBehaviorDto
import com.usian.model.behavior.pojos.ApCollection
import com.usian.model.common.base.BaseServiceImpl
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

@Service
open class ApCollectionServiceImpl : BaseServiceImpl<ApCollectionBehaviorMapper, ApCollection>() {
    @Autowired
    private lateinit var behaviorFeign: BehaviorFeign

    open fun collection(dto: CollectionBehaviorDto): ResponseResult<*> {
        if (dto.entryId == null || dto.articleId == null || dto.type < 0 || dto.type > 1 || dto.operation < 0 || dto.operation > 1) return paramError
        var entry = behaviorFeign.findByUserIdOrEquipmentId(dto.entryId.toInt(), dto.equipmentId
                ?: 0) ?: return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)
        var collection = getOne(Wrappers.query<ApCollection>().eq("entry_id", entry.id).eq("article_id", dto.articleId))
        if (collection == null) {
            if (dto.operation.toInt() == 1) return paramError
            save(ApCollection().apply {
                entryId = entry.entryId
                articleId = dto.articleId
                type = dto.type
                collectionTime = Date()
                publishedTime = Date()
            })
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)
        } else {
            return if (dto.operation.toInt() == 0)
                ResponseResult.okResult("该文章已经收藏")
            else {
                removeById(collection.id)
                ResponseResult.okResult("取消收藏成功")
            }
        }
    }
}
